package cn.itcast.www.jspservletTest;

import java.awt.print.Pageable;
import java.util.Collection;
import java.util.Iterator;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.TagSupport;
//迭代器标签
public class IterateTag extends TagSupport {
	private Iterator items;
	private String itemId;
	private Object item;
	
	public IterateTag(){
		items = null;
	}
	//释放占用系统资源
	public void release(){
		items = null;
	}
	//得到集合的迭代对象，集合变量参数
	public void setItems(Collection cl){
		if(cl.size() > 0)
			items = cl.iterator();
	}
	//var作为<iterate>标签的属性
	public void setVar(String var){
		itemId = var;
	}
	
	public int doStartTag(){
		if(items.hasNext()){
			item = items.next();
		}else{
			return SKIP_BODY;
		}
		putVariable();
		return EVAL_BODY_INCLUDE;
	}
	@Override
	public int doAfterBody() throws JspException {
		if(items.hasNext()){
			item = items.next();
		}else{
			return SKIP_BODY;
		}
		putVariable();
		return EVAL_BODY_AGAIN;
	}
	//将从集合中取出的元素保存到pageContext对象中
	public void putVariable(){
		if(null == item){
			pageContext.removeAttribute(itemId, PageContext.PAGE_SCOPE);
		}else{
			pageContext.setAttribute(itemId, item);
		}
	}
}
